import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import router from '../router'
import { 
  getToken, setToken, removeToken, 
  getUser, setUser, removeUser,
  getUserPermissions, setUserPermissions, removeUserPermissions,
  clearAuthData
} from '@/utils/auth'
import ApiService from '@/services/ApiService'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(getUser())
  const token = ref(getToken())
  const isAuthenticated = ref(!!token.value)
  const loading = ref(false)
  const error = ref(null)
  const userRoles = ref([])
  const userPermissions = ref(getUserPermissions())

  // 保存用户演示数据
  const users = ref([
    {
      id: 1,
      username: 'admin',
      password: 'admin123',
      email: 'admin@example.com',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      role: 'admin'
    },
    {
      id: 2,
      username: 'manager',
      password: 'manager123',
      email: 'manager@example.com',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      role: 'manager'
    },
    {
      id: 3,
      username: 'operator',
      password: 'operator123',
      email: 'operator@example.com',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      role: 'operator'
    },
    {
      id: 4,
      username: 'viewer',
      password: 'viewer123',
      email: 'viewer@example.com',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      role: 'viewer'
    }
  ])

  // 初始化 - 从本地存储恢复登录状态
  const initialize = () => {
    const savedUser = getUser()
    if (savedUser) {
      user.value = savedUser
      isAuthenticated.value = true
      userPermissions.value = getUserPermissions()
    }
  }

  // 加载用户角色和权限
  const loadUserRolesAndPermissions = async (userId) => {
    try {
      const roles = await ApiService.getUserRoles(userId)
      userRoles.value = roles
      
      // 提取所有权限
      const permissions = []
      roles.forEach(role => {
        if (role.permissions) {
          permissions.push(...role.permissions)
        }
      })
      
      // 去重权限
      userPermissions.value = [...new Set(permissions)]
      
      // 保存到localStorage
      setUserPermissions(userPermissions.value)
      
      return true
    } catch (err) {
      console.error('加载用户角色权限失败', err)
      ElMessage.warning('权限信息加载失败，部分功能可能不可用')
      return false
    }
  }

  // 登录方法
  const login = async (credentials) => {
    loading.value = true
    error.value = null
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 查找用户
      const foundUser = users.value.find(u => 
        u.username === credentials.username && u.password === credentials.password
      )
      
      if (!foundUser) {
        throw new Error('用户名或密码错误')
      }
      
      // 设置用户信息
      user.value = foundUser
      setUser(foundUser)
      
      // 加载用户角色和权限
      await loadUserRolesAndPermissions(foundUser.id)
      
      // 设置认证状态
      isAuthenticated.value = true
      
      // 保存token（实际应用中应该从后端获取）
      const mockToken = 'mock-token-' + Date.now()
      token.value = mockToken
      setToken(mockToken)
      
      ElMessage.success('登录成功')
      return true
    } catch (err) {
      error.value = err.message
      ElMessage.error(err.message)
      return false
    } finally {
      loading.value = false
    }
  }

  // 注册方法
  const register = async (userData) => {
    loading.value = true
    error.value = null

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 检查用户名是否已存在
      const existingUser = users.value.find(u => u.username === userData.username)
      if (existingUser) {
        error.value = '用户名已存在'
        ElMessage.error(error.value)
        return false
      }

      // 创建新用户
      const newUser = {
        id: users.value.length + 1,
        username: userData.username,
        password: userData.password, // 实际应用中应该加密
        email: userData.email,
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        role: 'viewer' // 默认为查看者角色
      }

      // 添加到用户列表
      users.value.push(newUser)
      return true
    } catch (err) {
      error.value = err.message || '注册失败'
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    user.value = null
    token.value = null
    isAuthenticated.value = false
    userRoles.value = []
    userPermissions.value = []
    
    // 使用工具函数清除状态
    clearAuthData()
    
    // 导航到登录页
    router.push('/login')
  }

  // 检查认证状态
  const checkAuth = () => {
    return isAuthenticated.value
  }

  // 检查是否有某个权限
  const checkPermission = (permission) => {
    if (!isAuthenticated.value) return false
    
    // 管理员拥有所有权限
    if (userPermissions.value.includes('*')) return true
    
    return userPermissions.value.includes(permission)
  }

  // 检查是否有任一权限
  const checkAnyPermission = (permissionList) => {
    if (!isAuthenticated.value) return false
    
    // 管理员拥有所有权限
    if (userPermissions.value.includes('*')) return true
    
    return permissionList.some(permission => userPermissions.value.includes(permission))
  }

  // 初始化
  initialize()

  return {
    user,
    token,
    isAuthenticated,
    loading,
    error,
    userRoles,
    userPermissions,
    login,
    register,
    logout,
    checkAuth,
    checkPermission,
    checkAnyPermission,
    loadUserRolesAndPermissions
  }
}) 